'use strict';

/**
 * Module dependencies
 */
var path = require('path'),
  mongoose = require('mongoose'),
  fs = require("fs"),
  Article = mongoose.model('Article'),
  errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller'));

var imgSavingPath = path.join(process.env.imgSavingPath, 'article-img');

var mkdirRecursive = module.exports.mkdirRecursive = function (dirpath) {
  if (!fs.existsSync(dirpath)) {
    //尝试创建父目录，然后再创建当前目录
    mkdirRecursive(path.dirname(dirpath));
    fs.mkdirSync(dirpath);
  }
};

mkdirRecursive(imgSavingPath);

/**
 * Create an article
 */
exports.create = function (req, res) {
  var article = new Article(req.body);
  article.user = req.user;

  var addImgs = req.files || [];
	addImgs.forEach(function (file) {
    var localFile = path.join(file.destination, file.filename);
    var dbFile = path.join(file.destination, file.filename + path.extname(file.originalname));
    var savingFile = path.join(imgSavingPath, file.filename + path.extname(file.originalname));

    // multer will save the img in the: uploads/article-img/xx
    // then move to c:\img\article-img\xx.img
    // but save the index in db: uploads/article-img/xx.img
    // client get the img, and the express's static function will redirect to c:\img\article-img\xx.img
    fs.renameSync(localFile, savingFile);
    article.imgs.push(dbFile);
  });

  var delImgs = req.params.delImgs || [];
	delImgs.forEach(function (fileName) {
	  var index = article._doc.imgs.indexOf(fileName);
	  if(index != -1) {
		  article.imgs.splice(index, 1);
	  }
	});

  article.save(function (err) {
    if (err) {
      return res.status(422).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.json(article);
    }
  });
};

/**
 * Show the current article
 */
exports.read = function (req, res) {
  // convert mongoose document to JSON
  var article = req.article ? req.article.toJSON() : {};

  // Add a custom field to the Article, for determining if the current User is the "owner".
  // NOTE: This field is NOT persisted to the database, since it doesn't exist in the Article model.
  article.isCurrentUserOwner = !!(req.user && article.user && article.user._id.toString() === req.user._id.toString());

  res.json(article);
};

/**
 * Update an article
 */
exports.update = function (req, res) {
  var article = req.article;

  article.title = req.body.title;
  article.content = req.body.content;
  article.category = req.body.category;
  article.outLink = req.body.outLink;
  article.toPublish = req.body.toPublish;
  article.store = req.body.store;

	var addImgs = req.files || [];
	addImgs.forEach(function (file) {
    var localFile = path.join(file.destination, file.filename);
    var dbFile = path.join(file.destination, file.filename + path.extname(file.originalname));
    var savingFile = path.join(imgSavingPath, file.filename + path.extname(file.originalname));

    fs.renameSync(localFile, savingFile);
    article.imgs.push(dbFile);
	});

	var delImgs = req.body.remImgList || [];
	delImgs.forEach(function (fileName) {
		var index = article._doc.imgs.indexOf(fileName);
		if(index != -1) {
			article.imgs.splice(index, 1);
		}
	});

  article.save(function (err) {
    if (err) {
      return res.status(422).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.json(article);
    }
  });
};

/**
 * Update an article's votes status
 */
exports.updateVotes = function (req, res) {
  var article = req.article;

  article.goodVotes = req.body.goodVotes;
  article.badVotes = req.body.badVotes;

  article.save(function (err) {
    if (err) {
      return res.status(422).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.json(article);
    }
  });
};

/**
 * Delete an article
 */
exports.delete = function (req, res) {
  var article = req.article;

  article.remove(function (err) {
    if (err) {
      return res.status(422).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.json(article);
    }
  });
};

/**
 * List of Articles
 */
exports.list = function (req, res) {

  var onlyListPublished = req.query.onlyListPublished;
  var dateTime = req.query.dateTime;
  var maxItem = req.query.maxItem;
  var query = null;

  // If onlyListPublished is false, means show all
  if(onlyListPublished.indexOf('true') !== -1) {
    query = Article.find({toPublish : true});
  }
  else {
    query = Article.find();
  }

  if(dateTime) {
    query.where('created').lt(dateTime);
  }

  query.sort('-created').limit(parseInt(maxItem)).populate('user', 'displayName').exec(function (err, articles) {
    if (err) {
      return res.status(422).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.json(articles);
    }
  });
};

/**
 * Article middleware
 */
exports.articleByID = function (req, res, next, id) {

  if (!mongoose.Types.ObjectId.isValid(id)) {
    return res.status(400).send({
      message: 'Article is invalid'
    });
  }

  Article.findById(id).populate('user', 'displayName').exec(function (err, article) {
    if (err) {
      return next(err);
    } else if (!article) {
      return res.status(404).send({
        message: 'No article with that identifier has been found'
      });
    }
    req.article = article;
    next();
  });
};
